package com.nf.practice.objecttest;

import lombok.Data;
import org.junit.jupiter.api.Test;

import java.lang.reflect.Method;

public class FS {

    @Test
    public void test() {
        Stu stu = new Stu();
        stu.setName("小明");
        stu.setNation("汉族");

        SerBody serBody = new SerBody();
        serBody.setRequest(stu);

        SevDoc sevDoc = new SevDoc();
        sevDoc.setUniversity("上海大学");
        sevDoc.setSerBody(serBody);

        Object request = sevDoc.getSerBody().getRequest();
        String name = (String) getFieldValueByName("name", request);
        System.out.println("反射获取name：" + name);
    }

    /**
     * 根据属性名获取属性值
     * */
    private Object getFieldValueByName(String fieldName, Object o) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter, new Class[] {});
            Object value = method.invoke(o, new Object[] {});
            return value;
        } catch (Exception e) {
            return null;
        }
    }

}

@Data
class SevDoc {
    private String university;
    private SerBody serBody;
}

@Data
class SerBody {
    private Object request;
}

@Data
class Stu {
    private String name;
    private String nation;
}